import { defineStore } from 'pinia';
import { computed, ref, watch } from 'vue';
import { UserInterface } from '@/typings/user';
import { USER } from '@/api/user';

export const useUserStore = defineStore('user', () => {
  const token = ref('');
  const user = ref({} as UserInterface);

  const isLoggedIn = computed(() => !!token.value && !!user.value.mobile);

  watch(token, (newValue, oldValue) => {
    if (newValue !== oldValue) {
      // 持久化存储token
      uni.setStorage({
        key: 'authorization_token_key',
        data: newValue
      });
    }
  });

  watch(user, (newValue) => {
    // 持久化存储user
    uni.setStorage({
      key: 'user_key',
      data: newValue,
      success: function () {
        console.log('success');
      }
    });
  });

  function setToken(t: string) {
    token.value = t;
  }

  function setUser(u: UserInterface) {
    user.value = u;
  }

  function initData() {
    uni.getStorage({
      key: 'authorization_token_key',
      success: function (res) {
        setToken(res.data);
      }
    });
    uni.getStorage({
      key: 'user_key',
      success: function (res) {
        setUser(res.data);
      }
    });
  }

  // 用户登录
  function login() {
    return new Promise((resolve) => {
      uni.login({
        provider: 'weixin',
        success: (res) => {
          resolve(res);
        }
      });
    });
  }

  function getUserInfo(code) {
    return new Promise((resolve) => {
      uni.request({
        url: `${import.meta.env.VITE_APP_BASE_API}${USER.GETOPENID}`,
        data: {
          jscode: code
        },
        timeout: 20000,
        method: 'GET',
        success: ({ data }) => {
          console.log(data.data, '成功');
          resolve(data.data || {});
        }
      });
    });
  }

  return {
    token,
    user,
    isLoggedIn,
    setToken,
    setUser,
    initData,
    login,
    getUserInfo
  };
});
